package com.gzu.azy.consumerWeighted;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.TreeMap;

@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/test-weight")
    public String testWeight(@RequestParam(defaultValue = "1000") int totalRequests) {
        TreeMap<String, Integer> instanceCountMap = new TreeMap<>();
        for (int i = 0; i < totalRequests; i++) {
            String response = restTemplate.getForObject("http://provide/value", String.class);
            String instanceName = "provider"+response;
            instanceCountMap.merge(instanceName, 1, Integer::sum);
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(String.format("Total requests: %d\n", totalRequests));
        instanceCountMap.forEach((name,value)->{
            stringBuilder.append(String.format("Instance %s: %d calls (%.2f%%)\n", name, value, value*100.0/totalRequests));
        });
        return stringBuilder.toString();
    }
}